package com.tedu.weibo.controller;

import com.fasterxml.jackson.databind.util.BeanUtil;
import com.tedu.weibo.mapper.UserMapper;
import com.tedu.weibo.pojo.dto.UserRegDTO;
import com.tedu.weibo.pojo.entity.User;
import com.tedu.weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/reg")
    public int reg(@RequestBody UserRegDTO userRegDTO){
        System.out.println(userRegDTO);
        User user = new User();
        //用户名称重复
        String username = userRegDTO.getUsername();
        User findUser = userMapper.selectByUsername(username);
        if(findUser != null){
            return 2;
        }
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return 1;
    }

    @PostMapping("/login")
    public int login(@RequestBody UserRegDTO userRegDTO , HttpSession session){

        System.out.println(userRegDTO);

        User user = userMapper.selectByUsername(userRegDTO.getUsername());
        if (user != null) {
            if (user.getPassword().equals(userRegDTO.getPassword())) {
                session.setAttribute("user",user);
                return 1;
            } else {
                return 2;
            }
        }else {
            return 3;
        }
    }

    @GetMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return null;
        }else {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user,userVO);
            return userVO;
        }

    }
    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }


}
